<template>
    <div class="content">
        <el-form label-width="60px">
            <div style="width: 100%">
                <el-row>
                    <el-col :span="3">
                        <el-form-item label="任务类别">
                            <el-select v-model="searchParams.taskType" size="mini" class="item" filterable clearable>
                                <el-option v-for="(value, key) in taskTypeOptions" :key="key" :value="key" :label="value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="3">
                        <el-form-item label="产品状态">
                            <el-select v-model="searchParams.fundOptStatusList" size="mini" class="item" filterable clearable multiple collapse-tags>
                                <el-option v-for="(value, key) in fundOptStatusPojo" :key="key" :value="key" :label="value"></el-option>
                            </el-select>
                        </el-form-item> 
                    </el-col>
                    <el-col :span="3">
                        <el-form-item label="产品类型">
                            <el-select v-model="searchParams.fundType" size="mini" class="item" filterable clearable>
                                <el-option v-for="(value, key) in fundTypeOptions" :key="key" :value="key" :label="value"></el-option>
                            </el-select>
                        </el-form-item>        
                    </el-col>
                    <el-col :span="3">
                        <el-form-item label="产品信息">
                            <RiskEntryInput
                                :url="'/ledger/fundInfo/list/byUser/like?fundCodeOrName='"
                                @set-entry-data="getEntryslist"
                                :itemKey="'fundProductCode'"
                                :returnDatas="searchParams.codeAndName"
                                class="item"
                                style="display:inline-block"
                            />  
                        </el-form-item>  
                    </el-col>
                    <el-col :span="3">
                        <el-form-item label="主办人">
                            <el-select v-model="searchParams.sponsor" size="mini" class="item" clearable filterable>
                                <el-option v-for="item in sponsors" :key="item.userCode" :value="item.userCode" :label="item.userName"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="3">
                        <el-form-item label="任务状态">
                            <el-select v-model="searchParams.statusList" size="mini" class="item" filterable clearable multiple collapse-tags>
                                <el-option v-for="(value, key) in statusOptions" :key="key" :value="key" :label="value"></el-option>
                            </el-select>
                        </el-form-item>        
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label-width="5px">
                            <el-button size="mini" type="primary" @click="handleBtn('search')">查询</el-button>
                            <el-button size="mini" @click="handleBtn('reset')">重置</el-button>
                            <el-button size="mini" @click="handleBtn('loadout')">导出</el-button>
                            <!-- <el-button size="mini" @click="handleBtn('exchangeBatch')">批量更改</el-button> -->
                        </el-form-item>    
                    </el-col>
                </el-row>
            </div>
        </el-form>
        <RiskTableP
            ref="risk-table"
            :tableConfig="tableConfig"
            :tableData="tableData"
            :column="tableColumns"
            :paging="paging"
            :searchParams="searchParams"
            v-loading="tableLoading"
            @page-change="getTableData"
            style="height:calc(100% - 85px)"
        >
            <!-- @cell-click="handleCellClick" -->
            <template #taskType="{ row }">
                <span class="cell-taskType" @click="handleCellClick('taskType', row)">{{ taskTypeOptions[row.taskType] || '--' }}</span>
            </template>
            <!-- <template #contractName="{ row }">
                <span class="cell-fundName">【{{ row.contractName }}】</span>
            </template> -->
            <!-- <template #operation="{ row }">
                <el-button type="text" @click="updateStatus([row.taskNo])" :disabled="row.status === '2'">修改状态</el-button>
            </template> -->
        </RiskTableP>
    </div>
</template>
<script lang="ts">
import RiskEntryInput from '@/common/components/risk-entry-input.vue';
import RiskTableP from '@/common/components/risk-table-plus.vue';
import { PageVO, TableConfigVO } from '@/common/vo';
import { downLoadFile } from '@/utils/request';
import { dateFormat } from '@/utils/tools';
import { getUser } from '@/utils/user-util';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import * as api from '../api/fund-pending-manage';
import DictionConstUtil from '../dict';

@Component({ name: 'TaskDetail', components: { RiskTableP, RiskEntryInput } })
export default class TaskDetail extends Vue {
    @Prop() echartParams: any;
    searchParams: any = {
        taskType: '',
        fundType: '',
        codeAndName: '',
        sponsor: getUser().userCode,
        statusList: [],
        fundOptStatus: '',
        weekFlag: '0',
        year: '',
        month: '',
        contractType: '',
        fundOptStatusList: []
    };
    tableLoading: boolean = true;
    tableConfig: TableConfigVO = {
        rowKey: 'taskNo', // 主键key TODO
        allRowKeys: [], // 所有页数据的key集合
    };
    tableData: any[] = [
        // {
        //     taskNo: '134',
        //     taskType: '1',
        //     fundName: '产品简称2023号',
        //     status: '1',
        // },
        // {
        //     taskNo: '678',
        //     taskType: '1',
        //     fundName: '产品简称2023号',
        //     status: '2',
        // },
    ];
    tableColumns = [
        {
            type: 'checkbox',
            selectedAll: false,
            fixed: 'left',
            align: 'center',
            width: 60,
        },
        {
            title: '待办任务类别',
            field: 'taskType',
            minWidth: 130,
            // render: value => this.taskTypeOptions[value],
            align: 'center',
        },
        {
            title: '产品代码',
            field: 'fundCode',
            minWidth: 80,
        },
        {
            title: '产品简称',
            field: 'fundName',
            minWidth: 160,
        },
        { 
            title: '产品状态',
            minWidth: '100px', 
            field: 'fundOptStatus', 
            render: value => this.fundOptStatusPojo[value]
        },
        {
            title: '产品类型',
            field: 'fundType',
            minWidth: 100,
            render: value => value && value.join(','),
            // render: value => {
            //     if (value) {
            //         return value.map(key => this.fundTypeOptions[key]).join(',');
            //     } else {
            //         return '--';
            //     }
            // },
            align: 'center',
        },
        {
            title: '合同名称',
            field: 'contractName',
            minWidth: 180,
        },
        {
            title: '合同上传日期',
            field: 'uploadDate',
            minWidth: 100,
            align: 'center',
            render: value => dateFormat(value),
        },
        {
            title: '合同生效日期',
            field: 'takeEffectDate',
            minWidth: 100,
            align: 'center',
            render: value => dateFormat(value),
        },
        {
            title: '主办人',
            field: 'sponsor',
            minWidth: 100,
        },
        {
            title: '办理完成日期',
            field: 'finshDate',
            minWidth: 100,
            align: 'center',
            render: value => dateFormat(value),
        },
        {
            title: '任务状态',
            field: 'status',
            minWidth: 100,
            align: 'center',
            render: value => this.statusOptions[value],
        },
        // {
        //     title: '操作',
        //     field: 'operation',
        //     fixed: 'right',
        //     width: 90,
        //     align: 'center',
        // },
    ];

    paging: PageVO = {
        currentPage: 1,
        pageSize: 25,
        total: 0,
    };

    taskTypeOptions = DictionConstUtil.taskTypeOptions;

    fundTypeOptions = DictionConstUtil.fundTypeOptions;

    fundOptStatusPojo = DictionConstUtil.fundOptStatusPojo;

    statusOptions = DictionConstUtil.statusOptions;

    sponsors: { userCode: string; userName: string }[] = [];

    @Prop() activeValue: string;
    isFirst: boolean = true;
    @Watch('activeValue', { immediate: true })
    async handleActiveValue() {
        // 手动点击切换
        if (this.activeValue === 'task-detail') {
            if (this.isFirst) {
                try {
                    await this.getUser();
                } finally {
                    if (this.echartParams.isClick) {
                        this.getTableData();
                    }
                }
                this.isFirst = false;
            }
        }
    }

    @Watch('echartParams', { deep: true })
    handleEchartParams() {
        // 点击柱状图切换tab标签
        if (this.activeValue === 'task-detail' && !this.echartParams.isClick) {
            const keys = Object.keys(this.searchParams);
            const params = this.echartParams.params;
            for (let key of keys) {
                this.searchParams[key] = params[key] || '';
            }
            this.getTableData();
        }
    }
    /**
     * 修改状态
     */
    updateStatus(taskNos: any, alreadyKeys: any = []) {
        const alrName = alreadyKeys.length > 0 ? alreadyKeys + '已办理,' + taskNos + '待办理,' : '';
        this.$msgbox({
            title: '提示信息',
            message: `${alrName}确定办理完成?`,
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            showCancelButton: true,
            closeOnClickModal: false,
            closeOnPressEscape: false,
            beforeClose: (action, instance, done) => {
                if (action === 'confirm') {
                    instance.confirmButtonLoading = true;
                    instance.confirmButtonText = '执行中...';
                    setTimeout(() => {
                        done();
                        setTimeout(() => {
                            instance.confirmButtonLoading = false;
                        }, 300);
                    }, 3000);
                } else {
                    done();
                }
            },
        })
            .then(() => {
                // TODO 处理状态修改接口
                api.taskStatusUpdate({ taskNo: taskNos })
                    .then((res: any) => {
                        this.yh_message_success('操作成功!');
                        this.getTableData();
                        this.$nextTick(() => {
                            (this.$refs['risk-table'] as any).resetCheckRowKeys();
                        });
                    })
                    .catch(() => {});
            })
            .catch(() => {});
    }

    /**
     * 表格数据
     */
    getTableData(type?: string) {
        this.tableLoading = true;
        api.taskDetail({ ...this.searchParams, paging: this.paging })
            .then((res: any) => {
                this.tableData = res?.list || [];
                this.paging.total = res?.total || 0;
            })
            .catch(() => {
                // const res = {
                //     list: [
                //         {
                //             status: '1',
                //             taskNo: '123',
                //         },
                //         {
                //             status: '2',
                //             taskNo: '234',
                //         },
                //         {
                //             status: '1',
                //             taskNo: '456',
                //         },
                //     ],
                //     total: 3,
                // };
                // this.tableData = res?.list || [];
                // this.paging.total = res?.total || 0;
            })
            .finally(() => {
                this.tableLoading = false;
            });
    }

    /**
     * 按钮点击
     */
    async handleBtn(type: string) {
        if (type == 'search') {
            // 点击查询时清除跳转带过来的参数
            this.searchParams.fundOptStatus = '';
            this.searchParams.weekFlag = '0';
            this.searchParams.year = '';
            this.searchParams.month = '';
            this.searchParams.contractType = '';

            this.paging.currentPage = 1;
            this.getTableData('search');
            this.$nextTick(() => {
                (this.$refs['risk-table'] as any).resetCheckRowKeys();
            });
        } else if (type == 'loadout') {
            const checkRowKeys = (this.$refs as any)['risk-table'].checkRowKeys || [];
            await downLoadFile({
                url: '/agent/task/detail/export',
                method: 'post',
                data: checkRowKeys.length ? { taskNo: checkRowKeys } : this.searchParams,
            });
            this.$nextTick(() => {
                (this.$refs['risk-table'] as any).resetCheckRowKeys();
            });
        } else if (type == 'exchangeBatch') {
            let checkedRows = (this.$refs as any)['risk-table'].checkedRows || [];
            if (checkedRows.length < 1) {
                this.yh_message_info('请先勾选需批量更改的数据');
                return;
            }

            let realBatKeys = [];
            let alreadyKeys = [];
            checkedRows.map(item => {
                if (item.status == '1') {
                    realBatKeys.push(item.taskNo);
                } else {
                    alreadyKeys.push(item.taskNo);
                }
                return item;
            });

            this.updateStatus(realBatKeys, alreadyKeys);
        } else if (type == 'reset') {
            this.searchParams = {
                taskType: '',
                fundType: '',
                codeAndName: '',
                sponsor: '',
                statusList: [],
                fundOptStatus: '',
                weekFlag: '0',
                year: '',
                month: '',
                contractType: '',
                fundOptStatusList: []
            };
        }
    }

    /**
     * 单元格字段点击
     */
    handleCellClick(property, row) {
        if (property == 'taskType') {
            let tab = 'source';
            if (row[property] == '1') {
                tab = 'source';
            } else {
                tab = 'clause';
            }
            const data = {
                type: 'task-detail',
                ...row,
                fundCode: row.indexDirectoryCode,
                tab,
            };
            this.JumpRoute('/vue/indexManage/ComplianceSource', '合规性指标中心', data);
        }
    }

    JumpRoute(menuUrl, menuName, data) {
        let obj = getUser().resources.find(item => item.menuUrl == menuUrl);
        if (obj) {
            // 合规条款库维护->【产品合同】,交易系统维护、事后系统维护->【合同条款】
            let msg = {
                type: 'compliance-source',
                path: '/vue/indexManage/ComplianceSource',
                title: '指标中心',
                params: '&fundCode=' + data.fundCode + '&tab=' + data.tab,
            };
            top.window.postMessage(msg, '*');
        } else {
            this.yh_message_error(`无${menuName}页面权限,不可跳转!`);
        }
    }

    // 产品代码
    getEntryslist(val: any) {
        this.searchParams.codeAndName = val;
    }

    // 主办人下拉数据
    getUser() {
        return new Promise((resolve, reject) => {
            api.taskDetailUser()
                .then((res: any) => {
                    const obj = res.find(item => item.userCode == getUser().userCode);
                    if (!obj) {
                        // 当前用户不为主办人时，展示全部
                        this.searchParams.sponsor = '';
                    }
                    this.sponsors = res;
                    resolve(res);
                })
                .catch(err => {
                    this.searchParams.sponsor = '';
                    reject(err);
                });
        });
    }
}
</script>
<style lang="scss" scoped>
.content {
    padding: 10px;
    .form {
        display: grid;
        grid-template-columns: repeat(6, 2fr) 3fr;
        // .el-select--mini {
        //     width: 50%;
        // }
        border: 1px solid #ccc;
        padding: 8px;
        margin-bottom: 10px;
        .el-form-item {
            margin-bottom: 0px;
            &:last-of-type {
                display: flex;
                align-items: center;
                /deep/ .el-form-item__content {
                    display: flex;
                    height: 32px;
                }
            }
        }

        .item {
            width: 55%;
        }
    }
}
.cell-fundName {
    cursor: pointer;
    &:hover {
        color: #409eff;
    }
}
.cell-taskType {
    cursor: pointer;
}
/deep/ .el-select__tags-text {
    display: inline-block;
    max-width: 25px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
/deep/ .el-tag__close.el-icon-close {
    top: -5px;
}
/deep/ .el-form-item {
    margin-bottom: 3px;
}
</style>
<style>
.el-message-box__message {
    text-align: center;
}
</style>
